<?php
namespace Services;
use Misc\Tools;

/**
 * File holds class for User data manipulation
 *
 * PHP version 5.3.5
 *
 * @category   CM
 * @package    Services
 * @subpackage -
 * @author     markus karileet <markuskarileet@hotmail.com>
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL
 * @link       -
 */
class User extends ORM {
	/**
	 * Method searches user by email or phone. When user is found, then it is
	 * returned, otherwise false
	 * @param var $email
	 * @param var $phone
	 * @return \Entities\User on success, false on error
	 */
	public function findUserByEmailOrPhone($email, $phone) {
		$this->_logger->debug('Trying to map new user with existing user');
		$dbUser = false;
		//first off try to find user by email
		if (strlen($email) > 0) {
			$user = new \Entities\User();
			$user->setEmail(Tools::cleanInput($email));
			$dbUser = $this->select($user);
		}
		//then try to find user by phone
		if (strlen($phone) > 0 && !$dbUser) {
			$user = new \Entities\User();
			$user->setPhone(Tools::cleanInput($phone));
			$dbUser = $this->select($user);
		}
		
		//when user is found, return it, otherwise false
		return $dbUser;
	}
	
	/**
	 * Method prepares data for user storing
	 * @param array $post HTML POST array
	 * @return int ID after successful insert, or 0 when problems 
	 * @throws \Exception 
	 */
	public function prepareInsert($post) {
		$id = 0;
		if (isset($post['email']) || isset($post['phone'])) {
			$user = new \Entities\User();
			$user->setPhone(Tools::cleanInput($post['phone']));
			$user->setEmail(Tools::cleanInput($post['email']));
			$id = $this->insert($user);
		}
		return $id;
	}
}